package my.shadowsocks.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import my.shadowsocks.common.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author fengbo
 * @date 2018/9/28
 */
public class SocksServer {

    private static final Logger log = LoggerFactory.getLogger(SocksServer.class);

    private final int port;

    private SocksServer(int port) {
        this.port = port;
    }

    private void start() {
        EventLoopGroup bossGroup = new EpollEventLoopGroup(1);
        EventLoopGroup workGroup = new EpollEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup).channel(EpollServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) {
                            channel.pipeline().addLast(new BouncyCastleCodec());
                            channel.pipeline().addLast(new HostHandler());
                        }
                    });

            log.info("listener port = {}", port);

            bootstrap.bind(port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        Config config = Config.getInstance();
        config.init(SocksServer.class.getClassLoader().getResourceAsStream("config.properties"));

        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = config.getIntValue("server.port", 100);
        }

        new SocksServer(port).start();
    }

}
